package com.book.servlet.auth;

import com.book.service.AdminService;
import com.book.service.impl.AdminServiceImpl;
import com.book.utils.ThymeleafUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import org.thymeleaf.context.Context;

import java.io.IOException;
import java.util.Objects;

@WebServlet(name = "RegisterServlet", value = "/register")
public class RegisterServlet extends HttpServlet {

    AdminService adminService;

    @Override
    public void init() throws ServletException {
        adminService=new AdminServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Context context = new Context();
        if (Objects.nonNull(request.getSession().getAttribute("register-failure"))) {
            context.setVariable("failure", true);
        }
        ThymeleafUtil.process("register.html", context, response.getWriter());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String nickname = request.getParameter("nickname");
        String password = request.getParameter("password");

        if (adminService.register(username,nickname,password)){
            response.sendRedirect("login");
        }else {
            request.getSession().setAttribute("register-failure",new Object());
            this.doGet(request, response);
        }
    }
}
